/**
 * *****************************************************************
 * @file    adt3102_i2c.c
 * @author  WuHao(hwu@andartechs.com.cn)
 * @version 1.0.0
 * @date    2020-11-24
 * @brief
 *
 *                 Copyright (c) 2020, Andar Technologies Inc.
 *                           www.andartechs.com 
 *
 * *****************************************************************
 */
/*------------------------------ include -------------------------------------*/
#include "stdio.h"
#include "adt3102_type_define.h"
#include "gpio_ctype_map.h"
#include "i2c_ctype_map.h"
#include "adt3102_i2c.h"
#include "adt3102_system.h"
#include "adt3102.h"


/*------------------------------ function ------------------------------------*/
/**
 * @brief   iic0 and iic1 setting.
 * @param   i2cX: iic include iic0 iic1.
 * @return  None.
 * @note
 */
void i2cInit(I2C_TypeDef *i2cX)
{
    if (i2cX == I2C0)
    {
        GPIO->gpio_p07_config=0x81;//i2c0scl
        GPIO->gpio_p08_config=0x81;//i2c0sda
	}else{
        GPIO->gpio_p17_config=0x81;//i2c1scl
        GPIO->gpio_p18_config=0x81;//i2c1sda
    }
    //i2c_i2cm_cfg[23:8]=  50M/(5*f)-1   100KHz=99=0x63.
    //1khz:2710  2khz:1388  3khz:D05
    i2cX->i2c_i2cm_cfg=0x3180;//I2C master config register
    i2cX->i2c_cfg=0xC0000;
}

/**
 * @brief   iic0 and iic1 receive 1byte data.
 * @param   i2cX: iic include iic0 iic1.
 * @return  None.
 * @note
 */
uint8 iicRecvByte(I2C_TypeDef *i2cX)
{
    uint8 receive;
    i2cX->i2c_i2cm_tar=0x50;
    i2cX->i2c_i2cm_cr=0xe8;
    receive=I2C0->i2cir_rfifo_rd_data;
    return receive;
}


void iicStart(I2C_TypeDef *i2cX)
{
    i2cX->i2c_i2cm_cr = 0x98;
}


void iicStop(I2C_TypeDef *i2cX)
{
    i2cX->i2c_i2cm_cr = 0x44;
}

void iicSlaveAddr(I2C_TypeDef *i2cX, uint8 writeAddr)
{
    i2cX->i2c_i2cm_tar = writeAddr;
}


/**
 * @brief   iic0 and iic1 send 1byte data.
 * @param   i2cX: iic include iic0 iic1.
 * @param   DataToWrite: Data written.
 * @return  None.
 * @note
 */
void iicSendByte(I2C_TypeDef *i2cX, uint8 DataToWrite)
{
    i2cX->i2c_i2cm_cr   = 0x98;
    i2cX->i2cir_tfifo_wr_data = DataToWrite;
    delayUs(500, HIGH_CLOCK_125M);
    i2cX->i2c_i2cm_cr   = 1 << 6;
}
